<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      class Subject {
        constructor(name, state = "send") {
          this.name = name;
          this.state = state; //被观察的状态
          //存放观察者队列
          this.observers = [];
        }
        //存放观察者的事件
        attach(observer) {
          this.observers.push(observer);
        }
        //设置新的状态时，通知所有的观察者
        setState(state) {
          this.state = state;
          this.observers.forEach((item) => {
            item.watch(this);
          });
        }
      }
      class Observer {
        constructor(name) {
          this.name = name;
        }
        watch(subject) {
          console.log(
            `${this.name}观察：${subject.name} 行为是：${subject.state}`
          );
        }
      }
      //被观察者的实例
      let subject = new Subject("接口一", "send");

      //生成观察者实例
      let clientA = new Observer("客户端A");
      let clientB = new Observer("客户端B");

      //让客户端A观察接口一
      subject.attach(clientA);
      //让客户端B观察接口一
      subject.attach(clientB);

      subject.setState("receive");
      //客户端A观察：接口一 行为是：receive
      //客户端B观察：接口一 行为是：receive
    </script>
  </body>
</html>
